package com.xiaotu.spider.maoyan.pageprocessor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.xiaotu.common.exception.SpiderException;
import com.xiaotu.common.exception.SpiderExceptionCode;
import com.xiaotu.common.model.MaoYanMovieCityCinemaBoxModel;
import com.xiaotu.common.util.CacheHandler;
import com.xiaotu.common.util.Constants;
import com.xiaotu.common.util.DateUtils;
import com.xiaotu.common.util.PageUtils;
import com.xiaotu.common.util.PropertiesUtil;
import com.xiaotu.common.util.RegexUtils;
import com.xiaotu.common.util.UUIDUtils;
import com.xiaotu.spider.APageProcessor;

import net.sf.json.JSONObject;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.selector.Html;

/***
 * 影投票房
 */
@Component("MaoYanMovieShadowBoxPageProcessor")
public class MaoYanMovieShadowBoxPageProcessor extends APageProcessor {

	
	private Map<String,String> cookies = new HashMap<String,String>();
	
	{
		cookies.put("Cookie", PropertiesUtil.getProperty("BoxOffice.site.Cookie"));
	}
	
	private String CITY_URL = "http://piaofang.maoyan.com/movie/%s/shadowBox?date=%s";//分城票房

	@Autowired
	private CacheHandler cacheHandler;
	
	@Override
	public void process(Page page) {
		
		Map<String, Object> extrasMap = page.getRequest().getExtras();
		
		switch (this.getPageDataType(page))
        {
            case Constants.PageDataType.MOVIE_COMPANY:
                this.cityProcess(page,extrasMap);
                break;
        }
	}
	
	/**
     * 分城数据爬取(因为影投数据的页面结构与分城相似，故写在一起)
     * @param page
     */
    private void cityProcess(Page page,Map<String, Object> extrasMap)
    {
    	
    	String filed = extrasMap.get("dataid").toString()+"_"+extrasMap.get("playdate")+"_"+extrasMap.get("playtype").toString();
    	
    	//将缓存数据删除
    	cacheHandler.hDel("MAOYAN_SHADOW_BOX", filed);
    	//redisClient.hset("MAOYAN_SHADOW_BOX_SUCCESS", filed, extrasMap.get("param_obj").toString());
		//当前页面的日期
    	String currPageDate = page.getHtml().xpath("//span[@class='m-calendar-querydate ']/@rawdate").get();
    	//当前请求日期
    	String currParamDate = DateUtils.matchDate(RegexUtils.REGEX_DATE,page.getRequest().getUrl());
    	
    	if(null == currPageDate || currPageDate.equals("unde-fi-ned")){
    		throw new SpiderException(SpiderExceptionCode.DataInvalideException);
    	}
    	
    	if(RegexUtils.regexMatch(RegexUtils.REGEX_DATE, currPageDate) && 
    			RegexUtils.regexMatch(RegexUtils.REGEX_DATE, currParamDate)){
    		if(!currPageDate.equals(currParamDate)){
    			throw new SpiderException(SpiderExceptionCode.DataInvalideException);
    		}
    	}else{
    		throw new SpiderException(SpiderExceptionCode.DataInvalideException);
    	}
    	
        List<String> areaNameList = page.getHtml().xpath
                ("//div[@class='t-main-col']/div[@class='t-row']/div[@class='t-col']/span/text()").all();
        
        if (areaNameList == null || areaNameList.isEmpty()) {
        	throw new SpiderException(SpiderExceptionCode.DataInvalideException);
        }
        Html html = null;
        try {
        	html = PageUtils.spiderAudienceRating(page,cookies);
		} catch (Exception e) {
			Map<String, Object> param = new HashMap<String,Object>();
			param.put("dataid", extrasMap.get("dataid").toString());
			param.put("mvname", extrasMap.get("mvname").toString());
			param.put("playdate", extrasMap.get("playdate").toString());
			param.put("playtype", extrasMap.get("playtype").toString());
			cacheHandler.hSet("MAOYAN_SHADOW_BOX", filed, param);
			Thread.currentThread().interrupt();
		}
        List<String> boxList = html.xpath("//div[@class='t-change-wrapper']//div[@class='t-row']")
                .all();
        if (boxList == null || boxList.isEmpty() || boxList.size() != areaNameList.size())
            throw new SpiderException(SpiderExceptionCode.DataInvalideException);
        List<MaoYanMovieCityCinemaBoxModel> cityList = new ArrayList<MaoYanMovieCityCinemaBoxModel>();
        for(int i = 0;i<areaNameList.size();i++)
        {
            List<String> valueList = new Html(boxList.get(i)).xpath("//i/text()").all();
            if (valueList.size() != 9)
                throw new SpiderException(SpiderExceptionCode.DataInvalideException);
            
            MaoYanMovieCityCinemaBoxModel maoYanMovieCityCinemaModel = new MaoYanMovieCityCinemaBoxModel(
            		currParamDate,
            		UUIDUtils.getId(),
            		extrasMap.get("dataid").toString(),
            		extrasMap.get("mvname").toString(),
            		areaNameList.get(i),
                    valueList.get(0).replaceAll("[--]", "").equals("")?"":valueList.get(0)+"万",
                    valueList.get(1).replace("--", ""), 
                    valueList.get(2).replace("--", ""), 
                    valueList.get(3).replace("--", ""),
                    valueList.get(4).replace("--", ""),
                    valueList.get(5).replace("--", ""),
                    valueList.get(6).replace("--", ""),
                    valueList.get(7).replace("--", ""),
                    valueList.get(8).replace("--", ""));
            		cityList.add(maoYanMovieCityCinemaModel);
        };
        page.putField(MaoYanMovieCityCinemaBoxModel.class.getName() + (Constants.PageDataType.MOVIE_COMPANY), cityList);
    }
	
	@Override
	protected Request getStartRequest(JSONObject target){
		Request	req = new Request(String.format(CITY_URL, target.getInt("dataid"), target.getString("playdate")));
		return req;
	};

	@Override
	protected String getSpiderType() {
		return Constants.SpiderTaskType.MOVIE_BOXOFFICE;
	}

	@Override
	public String getPageDataType(Page page) {
		String url = page.getUrl().toString();
        if (url.contains("/shadowBox"))
            return Constants.PageDataType.MOVIE_COMPANY;
        return null;
	}
	
}
